package com.xinghanlaser.applet.base.auth.security.component;


import com.xinghanlaser.applet.base.auth.entity.RoleDO;
import com.xinghanlaser.applet.base.auth.entity.UserDO;
import com.xinghanlaser.applet.base.auth.service.IUserService;
import com.xinghanlaser.applet.base.auth.vo.UserDetailVO;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

import static com.xinghanlaser.applet.base.auth.constant.AdminConstant.ENABLE;

/**
 * <p>
 * 处理security用户查询
 * <p>
 *
 * @author: mftuo 陀铭峰
 * @since: 2024/4/29 13:46
 */
@Component
public class MyUserDetailsService implements UserDetailsService {

    public static final String ROLE_PREFIX = "ROLE_";

    @Resource
    private IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetailVO userDetail = userService.queryUserDetail(new UserDO().setUserName(username));

        if (userDetail == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        return buildUserDetails(userDetail);
    }

    private UserDetails buildUserDetails(UserDetailVO userDetail) {
        return new org.springframework.security.core.userdetails.User(
                userDetail.getUserName(),
                userDetail.getPassword(),
                Objects.equals(userDetail.getIsEnable(), ENABLE),
                true,
                true,
                true,
                convertGrantedAuthorities(userDetail)
        );
    }

    private Collection<? extends GrantedAuthority> convertGrantedAuthorities(UserDetailVO userDetail) {
        List<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (RoleDO role : userDetail.getRoles()) {
            grantedAuthorities.add(new SimpleGrantedAuthority(joinAuthorityPrefix(role.getRoleCode())));
        }

        return grantedAuthorities;
    }

    private String joinAuthorityPrefix(String authority) {
        return ROLE_PREFIX + authority;
    }

}
